package com.southminority.ethnic.controller.student;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.southminority.ethnic.common.result.R;
import com.southminority.ethnic.controller.student.vo.ArticlePageVo;
import com.southminority.ethnic.controller.student.vo.StudentPageReqVo;
import com.southminority.ethnic.pojo.StudentArticle;
import com.southminority.ethnic.service.student.StudentArticleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 学生作品用户端控制器
 * 
 * @author SouthMinority
 */
@Slf4j
@Tag(name = "学生作品模块（用户端）", description = "学生作品查询接口")
@RestController
@RequestMapping("/student/article")
@CrossOrigin
public class StudentArticleController {
    
    @Autowired
    private StudentArticleService studentArticleService;

    /**
     * 分页查询学生作品列表（优化版，不返回完整内容）
     * @param reqVo 分页请求参数
     * @return 分页结果
     */
    @Operation(summary = "分页查询学生作品列表")
    @PostMapping("/page")
    public R<Page<ArticlePageVo>> getArticlePage(@Valid @RequestBody StudentPageReqVo reqVo) {
        try {
            Page<ArticlePageVo> result = studentArticleService.getArticlePage(
                reqVo.getPageNum(), 
                reqVo.getPageSize(), 
                reqVo.getKeyword(),
                    1
            );
            return R.ok(result);
        } catch (Exception e) {
            log.error("查询学生作品列表失败", e);
            return R.fail("查询失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID查询学生作品详情（包含完整内容）
     * @param id 作品ID
     * @return 作品详情
     */
    @Operation(summary = "查询学生作品详情")
    @GetMapping("/{id}")
    public R<StudentArticle> getArticleById(@PathVariable Long id) {
        try {
            StudentArticle article = studentArticleService.getById(id);
            if (article == null || article.getIsDeleted() == 1 || article.getStatus() != 1) {
                return R.fail("作品不存在或已下架");
            }
            // 增加浏览次数
            studentArticleService.incrementViews(id);
            return R.ok(article);
        } catch (Exception e) {
            log.error("查询学生作品详情失败", e);
            return R.fail("查询失败: " + e.getMessage());
        }
    }
}
